/**
 * Filename: JoinAlbumActivity.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/3/10 15:25
 */
package com.github.postsanf.yinian.activity;

import android.annotation.TargetApi;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.flaviofaria.kenburnsview.KenBurnsView;
import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.BaseApplication;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.ISkinUpdate;
import com.github.postsanf.yinian.utils.DisplayUtils;
import com.github.postsanf.yinian.utils.SkinPackageManager;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.LinkedHashMap;

/**
 * 加入相册
 */
public class JoinAlbumActivity extends BaseActivity implements View.OnClickListener, ISkinUpdate {
    private Toolbar mToolbar;
    private RelativeLayout rl_join_root;
    private EditText et_invite_code;
    private ImageView iv_invite_delete;
    private Button btn_submit_join;
    private String mCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yn_activity_join_album);
        BaseApplication.getInstance().mActivitys.add(this);
        initView();
        final Intent intent = getIntent();
        final Uri uri = intent.getData();
        if (uri != null) {
            mCode = uri.toString();
            mCode = mCode.substring(mCode.indexOf("=") + 1, mCode.length());
            try {
                et_invite_code.setText(URLDecoder.decode(mCode, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        if (application.getCurID() <= 0) {
            intent2Activity(SplashActivity2.class);
        }
    }

    private void initView() {
        mToolbar = (Toolbar) findViewById(R.id.join_album_toolbar);
        setSupportActionBar(mToolbar);
        mToolbar.setNavigationIcon(R.drawable.ic_return);
        rl_join_root = (RelativeLayout) findViewById(R.id.rl_join_root);
        et_invite_code = (EditText) findViewById(R.id.et_invite_code);
        iv_invite_delete = (ImageView) findViewById(R.id.iv_invite_delete);
        btn_submit_join = (Button) findViewById(R.id.btn_submit_join);
        iv_invite_delete.setOnClickListener(this);
        btn_submit_join.setOnClickListener(this);
        rl_join_root.setOnClickListener(this);
        et_invite_code.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() <= 0) {
                    iv_invite_delete.setVisibility(View.GONE);
                } else {
                    iv_invite_delete.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.rl_join_root:
                DisplayUtils.setFoucs(rl_join_root);
                break;
            // 申请入组
            case R.id.btn_submit_join:
                doJoinGroup();
                break;
            case R.id.iv_invite_delete:
                et_invite_code.setText("");
                iv_invite_delete.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }

    private void doJoinGroup() {
        if (doCheack()) {
            LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
            mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
            mParam.put(CommonConstants.YNS_INVITE_CODE, et_invite_code.getText().toString().trim());
            StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynApplyGroup))
                    .setMethod(HttpMethods.Post)
                    .setParamMap(mParam)
                    .setHttpListener(new HttpListener<String>(true, false, true) {
                        @Override
                        public void onSuccess(String s, Response<String> response) {
                            int code = 0;
                            String msg = "";
                            try {
                                JSONTokener jsonParser = new JSONTokener(s);
                                JSONObject res = (JSONObject) jsonParser.nextValue();
                                code = res.getInt("code");
                                msg = res.getString("msg");
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            switch (code) {
                                case 0:
                                    showToast(CommonConstants.TIP_SEND_SUCCESS);
                                    break;
                                case 2000:
                                    // 官方相册现在不加入主页
//                                    YNAlbumResponse resOfficial = gson.fromJson(s, YNAlbumResponse.class);
//                                    if (resOfficial!=null){
//                                        YNAlbum offiGroup = resOfficial.getData().get(0);
//                                        Intent upIntent = new Intent(ACTIONs.actionInvateGroup);
//                                        upIntent.putExtra(ACTIONs.aAlbumItem, offiGroup);
//                                        upIntent.putExtra(ACTIONs.IsAdd, true);
//                                        sendBroadcast(upIntent);
//                                    }
                                    break;
                                default:
                                    showToast(msg);
                                    break;
                            }
                            finish();
                        }

                        @Override
                        public void onFailure(HttpException e, Response<String> response) {
                            showToast(CommonConstants.YN_NET_LINK);
                        }
                    });
            liteHttp.executeAsync(req);
        }
    }

    private boolean doCheack() {
        String mCode = et_invite_code.getText().toString().trim();
        if (mCode.length() <= 0) {
            showToast("请输入正确邀请码");
            return false;
        }
        if (mCode.equals("天使")) {
            intent2Activity(YNWebActivity.class);
            finish();
            return false;
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void updateTheme() {
        if (mToolbar != null) {
            try {
                Resources mResource = SkinPackageManager.getInstance(this).mResources;
                mToolbar.setNavigationIcon(mResource.getDrawable(mResource.getIdentifier("ic_return", "drawable", "com.github.postsanf.skinby")));
                mToolbar.setBackgroundColor(mResource.getColor(mResource.getIdentifier("yncolor", "color", "com.github.postsanf.skinby")));
                mToolbar.setTitleTextColor(mResource.getColor(mResource.getIdentifier("border_color", "color", "com.github.postsanf.skinby")));
                btn_submit_join.setTextColor(mResource.getColorStateList(mResource.getIdentifier("txtcolor_white2theme", CommonConstants.THEME_DRAWABLE, CommonConstants.THEME_PACKAGE)));
                btn_submit_join.setBackground(mResource.getDrawable(mResource.getIdentifier("btn_invite_bg_sel", CommonConstants.THEME_DRAWABLE, CommonConstants.THEME_PACKAGE)));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BaseApplication.getInstance().mActivitys.remove(this);
    }

    // 友盟统计
    public void onResume() {
        super.onResume();
        if (SkinPackageManager.getInstance(this).mResources != null) {
            updateTheme();
        }
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
